<?php
/**
 * @author chenshubo
 * 洋葱供应商订单
 */

namespace App\Service\OrderService\OrderRouteService;

use App\Service\Code\Normal;
use App\Model\PssModel\OrderSupplier;
use Service\AppService\IdService;
use App\Service\OrderService\BaseSupplierRouterService;
use App\Service\VendorClient\ShoponionApi\ShopOnionApiClient;

class Shoponion extends BaseSupplierRouterService
{
    /**
     * 订单的退款状态（5：待审核，10：一审通过（只包括客服一审通过），
     * 20：二审通过（包括客服二审通过和财务各种操作），
     * 30：售后完成，40：驳回申请（包括客服驳回和自主取消））
     */
    const REFUND_STATUS_SUC  = 30;
    const REFUND_STATUS_FAIL = 40;
    /**
     * 创建订单
     * @param array $param
     * @return mixed
     */
    public function createOrder($param = []) {
        //下单商品重组
        $supplierGoodsInfo = $param['supplierGoodsInfo'];
        $userGoodsList     = $supplierGoodsInfo['userGoodsList'];
        $goodsList         = $supplierGoodsInfo['goodsList'];
        $orderItems        = [];

        //按照仓区进行拆单
        $defaultStockGroupGoodsList = [];
        foreach ($goodsList as $item) {
            $defaultStockGroupGoodsList[$item['defaultStock']][] = $item;
            unset($item);
        }
        //限购查询判断字段 LimitBuyCount
        $isDelare = (
            (isset($param['order']['isOrderDeclare']) && $param['order']['isOrderDeclare'] == 1) ||
            (isset($param['order']['isPayDeclare']) && $param['order']['isPayDeclare'] == 1)
        ) ? true : false;
        //是否云仓商城
        $isShop       = isset($param['order']['isSplitOrder']) && $param['order']['isSplitOrder'] == 1 ? true : false;
        $supplierCode = '';
        foreach ($defaultStockGroupGoodsList as $item) {
            foreach ($item as $goodsInfo) {
                //限购数量
                $limitBuyCount         = $goodsInfo['limitBuyCount'] ?? 0;
                $supplierCommodityType = $goodsInfo['supplierCommodityType'];
                $skuCode               = $goodsInfo['skuCode'];
                $orderGoodsAll         = [];
                foreach ($userGoodsList[$skuCode] as $currentOrderGoods) {
                    //如果是下游渠道，做了支付单申报，需要判断限购数量必须大于购买数量
                    $goodsNum = $currentOrderGoods['goodsNum'];
                    if ($isDelare && !$isShop && $goodsNum > $limitBuyCount && $limitBuyCount > 0) {
                        return Normal::returnCode(Normal::FAIL, "做了支付单申报的电商平台，商品SKU自编码【{$skuCode}】购买数量需要小于等于限购数量");
                    }
                    //如果是云仓商城并且满足合并支付的情况，需要根据商品的限购数量对下单数量取余数
                    if ($isDelare && $isShop) {
                        if ($limitBuyCount > 0) {
                            $ceil_count = ceil($goodsNum / $limitBuyCount);
                            if ($ceil_count == 1) {
                                array_push($orderGoodsAll, $currentOrderGoods);
                            } else {
                                for ($i = 0; $i < $ceil_count; $i++) {
                                    if ($i == $ceil_count - 1) {
                                        $currentOrderGoods['goodsNum'] = $goodsNum - $limitBuyCount * ($ceil_count - 1);
                                    } else {
                                        $currentOrderGoods['goodsNum'] = $limitBuyCount;
                                    }
                                    array_push($orderGoodsAll, $currentOrderGoods);
                                }
                            }
                        } else {
                            array_push($orderGoodsAll, $currentOrderGoods);
                        }
                    } else {
                        array_push($orderGoodsAll, $currentOrderGoods);
                    }
                }

                foreach ($orderGoodsAll as $key => $goods) {
                    //生成供应商主单
                    $supplierCode                   = $param['supplierGoodsInfo']['supplierCode'];
                    $param['order']['supplier_psn'] = OrderSupplier::instance()->getCreateOrderSn($supplierCode);
                    $param['order']['supplier_csn'] = IdService::instance()->getOtherID();
                    //防止订单号重复问题,下游已申报，则使用下游的订单号作为中台子单号
                    if ($isDelare && !$isShop && $supplierCommodityType != GOODS_TYPE_YBMY) {
                        $param['order']['supplier_dsn'] = $param['order']['orderSn'];
                    } else {
                        $param['order']['supplier_dsn'] = IdService::instance()->getOtherID();
                    }

                    $param['order']['goods']          = [$goods];
                    $param['order']['isQueryExpress'] = 1;
                    $res                              = OrderSupplier::instance()->getSupplierCreateOrderData($param);
                    if ($res['code'] != Normal::SUC) {
                        return $res;
                    }
                    $orderItems[] = $res['data'];
                }
            }
        }

        return Normal::returnCode(Normal::SUC, "获取成功", [
            'supplierCode' => $supplierCode,
            'orderItems'   => $orderItems
        ]);
    }

    /**
     * 订单支付
     * @param array $param
     * @return mixed
     */
    public function orderPay( $param = [] )
    {
        return $this->callSdkApi(ShopOnionApiClient::class,$param['apiBody'])->createOrder($param);
    }

    /**
     * 订单取消
     * @param array $param
     * @return mixed
     */
    public function orderCancel( $param = [] )
    {
        return $this->callSdkApi(ShopOnionApiClient::class,$param['apiBody'])->cancelOrder($param);
    }

    /**
     * 订单售后
     * @param array $param
     * @return mixed
     */
    public function orderAfterSale( $param = [] )
    {
        return $this->callSdkApi(ShopOnionApiClient::class,$param['apiBody'])->orderAfterSale($param);
    }


    /**
     * 商品列表查询接口
     * @param array $param
     * @return mixed
     */
    public function queryGoodsList( $param = [] )
    {
        $res = $this->callSdkApi(ShopOnionApiClient::class,$param['apiBody'])->{__FUNCTION__}($param['queryBody']);
        if( $res['code'] != Normal::SUC ) {
            return $res;
        }
        return Normal::returnCode(Normal::SUC,"获取成功",[
            'total' => $res['data']['totalCounts'],
            'list'  => $res['data']['data'],
        ]);
    }

     /**
     * 获取物流信息
     * @param array $param
     */
    public function queryOrderExpress( $param = [] )
    {
        $queryBody = $param['queryBody'];
        $apiBody   = $param['apiBody'];
        $orderID   = $queryBody['orderID'];
        $orderInfo = OrderSupplier::instance()->info(['id'=>$orderID,'company_id'=>$queryBody['supplierID']]);
        if( empty($orderInfo) ) {
            return Normal::returnCode(Normal::FAIL,"订单信息不存在，请核对！");
        }
        $res = $this->callSdkApi(ShopOnionApiClient::class,$apiBody)->{__FUNCTION__}($orderInfo);
        if( $res['code'] != Normal::SUC ) {
            return Normal::returnCode(Normal::FAIL,$res['msg']);
        }

        if ($res['code'] != Normal::SUC) {
            return Normal::returnCode(Normal::FAIL, $res['msg']);
        }
        if (empty($res['data']['data'])) {
            return Normal::returnCode(Normal::FAIL, "还未发货");
        }
        $expressInfo = $res['data']['data'];
        if (!isset($expressInfo['logisticsCompany']) || empty($expressInfo['logisticsCompany'])) {
            return Normal::returnCode(Normal::FAIL, "还未发货");
        }
        if (!isset($expressInfo['logisticsNo']) || empty($expressInfo['logisticsNo'])) {
            return Normal::returnCode(Normal::FAIL, "还未发货");
        }
        $expressName = $expressInfo['logisticsCompany'];
        $expressNo   = $expressInfo['logisticsNo'];
        return Normal::returnCode(Normal::SUC, "已发货", [
            'expressInfo' => [
                'express_name' => mb_strtoupper($expressName, 'utf-8'),
                'express_sn'   => $expressNo,
            ],
        ]);
    }

    /**
     * 获取售后信息
     * @param array $param
     */
    public function queryOrderAfterSale( $param = [] )
    {
        $queryBody = $param['queryBody'];
        $apiBody   = $param['apiBody'];
        $orderID   = $queryBody['orderID'];
        $orderInfo = OrderSupplier::instance()->info(['id'=>$orderID,'company_id'=>$queryBody['supplierID']]);
        if( empty($orderInfo) ) {
            return Normal::returnCode(Normal::FAIL,"订单信息不存在，请核对！");
        }
        $res = $this->callSdkApi(ShopOnionApiClient::class,$apiBody)->{__FUNCTION__}($orderInfo);
        if ($res['code'] != Normal::SUC) {
            return Normal::returnCode(Normal::FAIL, $res['msg']);
        }
        if (empty($res['data']['data'])) {
            return Normal::returnCode(Normal::FAIL, "无售后数据");
        }
        $refundStatus = $res['data']['data']['refundStatus'];
        $updateData   = [];
        if ($refundStatus == self::REFUND_STATUS_SUC) {
            $updateData = [
                'order_push_status'       => 0,
                'order_push_remark'       => '售后完成',
                'order_push_result'       => '售后完成',
                'after_sale_async_status' => 2,
                'md'                      => time(),
            ];
        }
        if ($refundStatus == self::REFUND_STATUS_FAIL) {
            $updateData = [
                'order_push_remark'       => $res['data']['data']['failMsg'] ?? '驳回申请',
                'order_push_result'       => $res['data']['data']['failMsg'] ?? '驳回申请',
                'after_sale_async_status' => 2,
                'md'                      => time(),
            ];
        }
        if ($updateData) {
            $upRes = OrderSupplier::instance()->where('id', $param['order_id'])->update($updateData);
            if (!$upRes) {
                return Normal::returnCode(Normal::FAIL, "更新订单售后状态失败");
            }
        }
    }
}
